<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <body onload="todolist('all')" >
           <h1>待办事项清单</h1>
           <input name="name" type="radio" onchange=todolist('0')>未完成项
           <input name="name" type="radio" onchange=todolist('1')>已完成项
           <input name="name" type="radio" onchange=todolist('all') checked="checked">所有项<br/>
           <input type="text" id='list' placeholder="添加新事项">
           <input type='submit' value="+" onclick=submit()><br/>
           <input type="text" id='list_title' placeholder="删除事项">
           <input type='submit' value="删除" onclick=del_title()>
           <ul id="a">

           </ul>
       </body>


    <script>
       //展示待办事项
       function todolist(completed){
            fetch('/todos'+'?completed='+completed)
                .then(res=>res.json())
                .then(data=>{
                                document.getElementById("a").innerHTML='';
                                var operation=data.todos
                                console.log(operation)
                                for(var i=0;i<operation.length;i++){
                                    var opt='<li><input type="checkbox" name="'+operation[i].id+'"onchange="is_finish(this.name)"><span>'+operation[i].title+'</span></li>'
                                    document.getElementById('a').innerHTML+=opt;
                            }})
                            }

       //添加待办事项
       function submit(){
            var url='/todos'
            var headers={
                'Content-Type':'application/x-www-form-urlencoded'
            }
            var value=document.getElementById("list").value
            fetch(url,{
                method:"POST",
                body:"title="+value,
                headers:headers})
               .then(res=>res.json())
               .catch(error=>console.error("Error:",error))
               .then(function(data){
               console.log(data)
               console.log('title' in data);
               if('title' in data){
                  document.getElementById('a').value="";
                  todolist('all');

                }
                })
                }
        //待办事项完成
           function is_finish(id){
           fetch('/todos/mark_completed'+'?id='+id)
           .then(res=>res.json())
           .then(function(data){
                if('title' in data){
                todolist('all');
           }
           });
           }
           function del_title(){
           title = document.getElementById('list_title').value;
           fetch('/todos/del_title'+'?title='+title)
           .then(res=>res.json())
           .then(function(data){
                todolist('all');
           });
           }

</script>

</html>